package com.wolan;

import com.wolan.utils.DateUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.xml.crypto.dsig.DigestMethod;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.util.Date;

/**
 * Created by fei.chen on 2016/3/26.
 */
public class TestMD5 {
    public static void main(String[] args) throws Exception{
        String str = "123123";
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(str.getBytes());
        byte[] result = md5.digest();
        for(int i=0;i<result.length;i++){
            System.out.println(result[i]);
        }
        String dateStr = DateUtil.dateToString(new Date(), DateUtil.DATE_FORMAT);
        String encryptStr = "14" + dateStr;

        System.out.println(encodeUserKey(encryptStr));
        byte[] r = encryptStr.getBytes();
        for(int i=0;i<r.length;i++){
            System.out.println(r[i]);
        }
        String encodeKey = encodeUserKey(encryptStr);
        System.out.println(decodeUserKey(encodeKey));
    }


    public static String encodeUserKey(String plainText) throws Exception {
        return encodeBase64(new String(plainText + "ef8c3a8de61a8ade").getBytes());

    }

    public static String decodeUserKey(String plainText) throws Exception {
        if(StringUtils.isEmpty(plainText)) return "";
        String str = new String(decodeBase64(plainText));
        return str.replaceAll("ef8c3a8de61a8ade", "");
    }

    public static String encodeBase64(byte[]input) throws Exception{
        Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod= clazz.getMethod("encode", byte[].class);
        mainMethod.setAccessible(true);
        Object retObj=mainMethod.invoke(null, new Object[]{input});
        return (String)retObj;
    }

    public static byte[] decodeBase64(String input) throws Exception{
        Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod= clazz.getMethod("decode", String.class);
        mainMethod.setAccessible(true);
        Object retObj=mainMethod.invoke(null, input);
        return (byte[])retObj;
    }
}
